import axios from 'axios';
import config from '../../config/config.js';
import qs from 'qs'
import {Message} from 'view-design'

const HOST = config.apiOrigin;

const ajax = axios.create({
    // timeout: 50000,
});


ajax.interceptors.request.use(config => {
    return config;
}, error => {
    return Promise.reject(error);
});
//
//
ajax.interceptors.response.use(
    response => {
        // Vue.prototype.hideLoading()
        if(response.data && response.data.msg === '非法Token!') {
            Message.warning('Token错误：请重新登录' )
            setTimeout(() => {

                localStorage.clear();
                location.hash = '/'
                setTimeout(() => {
                    location.reload();
                }, 100)
            }, 1000)
        }

        return response.data;
    },
    error => {
        // Vue.prototype.hideLoading()
        Message.warning('请求错误：' + error)
        return Promise.reject(error);
    }
);

const util = {
    HOST,
    imgHost: HOST + '/management/commonDownload?url=',
    ajax,
    ajaxClear: axios.create(),

    tempTypeMap: {
        案件来源表: 1,
        立案表: 2,
        案件处理意见报告: 3,
        行政处罚结案报告: 4,
        行政处罚回执: 5,
        约谈申请表及通知书: 6,
        约谈笔录: 7
    },
    informUnitMap: {
        网络舆情告知函: 1,
        网络舆情预警函: 2,
        网信专报: 3,
        每日网络舆情: 4,
        网络舆情电子简报: 5,
        网络舆情参考: 6,
    },
    downloadFile: (url) => {
        const iframe = document.createElement("iframe");
        iframe.style.display = "none"; // 防止影响页面
        iframe.style.height = 0; // 防止影响页面
        iframe.src = url;
        document.body.appendChild(iframe); // 这一行必须，iframe挂在到dom树上才会发请求
        console.log('iframe', iframe)
        // 5分钟之后删除（onload方法对于下载链接不起作用，就先抠脚一下吧）
        setTimeout(()=>{
            iframe.remove();
        }, 5 * 60 * 1000);
    },
    getTime(time) {
        if(time) {
            return moment(time).format('YYYY-MM-DD HH:mm')
        }
        return ''
    },
};

/* ---------------- 使用接口 ---------------- */
util.get = (url, params) => {

    let headers = getHeaders();

    if (!url.includes('http')) {
        url = HOST + url;
    }

    return ajax({
        headers,
        url,
        method: 'GET',
        params: params
    })
};

util.post = (url, data, type) => {
    let headers = getHeaders();
    if (!url.includes('http')) {
        url = HOST + url;
    }

    if(type === 'formdata') {
        headers['Content-Type'] = 'application/x-www-form-urlencoded';
        data = qs.stringify(data)
    }

    return ajax({
        headers,
        url,
        method: 'POST',
        data: data
    })
};

util.postFile = (url, file, data) => {
    let headers = getHeaders();
    if (!url.includes('http')) {
        url = HOST + url;
    }

    var formData = new FormData();
    formData.append('file', file, file.name);

    if(data) {
        Object.keys(data).forEach(key => {
            formData.append(key, data[key]);
        })
    }

    headers['Content-Type'] = 'multipart/form-data';

    return ajax({
        headers,
        url,
        method: 'POST',
        data: formData
    })
};

/**
 * 获取headers
 * @returns {{}}
 */
function getHeaders() {
    let UserInfo = getUserInfo();

    let headers = {
        // 'Content-Type': 'application/x-www-form-urlencoded'
    };
    let postToken;

    if (UserInfo && UserInfo.token) {
        postToken = UserInfo.token;
    }

    if (postToken) {
        headers.token = '' + postToken;
    }

    return headers;
}

/**
 * 获取用户信息
 * @returns {{}}
 */
function getUserInfo() {

    let UserInfo = JSON.parse(localStorage.getItem('iotUserInfo'));
    return UserInfo || {};
}



export default util
